import 'package:flutter/material.dart';
import 'package:floor/floor.dart';
import 'package:sqflite/sqflite.dart' as sqflite;
import 'dart:async';
import 'dart:math';

import 'user.dart';
import 'user_dao.dart';
import 'database.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Floor Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  late AppDatabase database;
  List<User> users = [];

  @override
  void initState() {
    super.initState();
    _initDatabase();
  }

  Future<void> _initDatabase() async {
    final database = await $FloorAppDatabase.databaseBuilder('app_database.db').build();
    setState(() {
      this.database = database;
    });
  }

  Future<void> _addRandomUsers() async {
    final userDao = database.userDao;

    // 创建3个随机Person对象
    final random = Random();
    List<User> randomUsers = List.generate(3, (index) {
      return User(null, 'Person ${random.nextInt(100)}', random.nextInt(100));
    });

    for (var user in randomUsers) {
      await userDao.insertUser(user);
    }

    // 获取插入后的数据并更新UI
    // _getUsers();
  }

  Future<void> _getUsers() async {
    final userDao = database.userDao;
    final allUsers = await userDao.findAllUsers();
    setState(() {
      users = allUsers;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Floor Example'),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          ElevatedButton(
            onPressed: _addRandomUsers,
            child: Text('Add Random Users'),
          ),
          ElevatedButton(
            onPressed: _getUsers,
            child: Text('Show All Users'),
          ),
          Expanded(
            child: ListView.builder(
              itemCount: users.length,
              itemBuilder: (context, index) {
                return ListTile(
                  title: Text(users[index].name),
                  subtitle: Text('Age: ${users[index].age}'),
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}
